import axios from 'axios'

// API响应类型
export interface APIResult<T> {
  code: number
  message?: string
  data?: T
}

// 库存数量占比数据类型
export interface GoodsInventoryNumber {
  count: number
  showGoods: GoodsDto[]
}

export interface GoodsDto {
  goodsId: number
  percentage: number
  goodsName: string
}

// 库存金额占比数据类型
export interface InventoryAmountRatio {
  totalCount: number
  totalAmount: number
  goodsAmountRatios: GoodsAmountRatio[]
}

export interface GoodsAmountRatio {
  goodsId: number
  goodsName: string
  goodsNumber: string
  stockQuantity: number
  unitPrice: number
  totalAmount: number
  amountPercentage: number
}

// 出入库排名数据类型
export interface InOutboundRanking {
  statisticsType: string
  startDate?: string
  endDate?: string
  rankings: RankingItem[]
}

export interface RankingItem {
  rank: number
  goodsId: number
  goodsName: string
  goodsNumber: string
  totalQuantity: number
  operationCount: number
  isInbound: boolean
}

// 出入库统计数据类型
export interface InOutboundStatistics {
  startDate?: string
  endDate?: string
  totalInboundQuantity: number
  totalOutboundQuantity: number
  inboundOperationCount: number
  outboundOperationCount: number
  netInventoryChange: number
  dailyStatistics: DailyInOutStatistics[]
}

export interface DailyInOutStatistics {
  date: string
  inboundQuantity: number
  outboundQuantity: number
  netChange: number
}

// 库存预警数据类型
export interface LowStockAlert {
  totalAlertCount: number
  checkTime: string
  lowStockItems: AlertItem[]
}

export interface AlertItem {
  goodsId: number
  goodsName: string
  goodsNumber: string
  currentStock: number
  minStockLevel: number
  safeStockLevel: number
  alertLevel: number
  alertDescription: string
  stockGap: number
  alertTime: string
}

// 系统消息数据类型
export interface SystemMessage {
  messageId: string
  messageType: string
  title: string
  content: string
  quantity: number
  operatorName: string
  messageTime: string
  level: string
}

// 综合仪表板数据类型
export interface DashboardData {
  inventoryQuantityRatio: GoodsInventoryNumber
  inventoryAmountRatio: InventoryAmountRatio
  inboundRanking: InOutboundRanking
  outboundRanking: InOutboundRanking
  lowStockAlert: LowStockAlert
  recentStatistics: InOutboundStatistics
  lastUpdated: string
}

/**
 * 统计数据API服务类
 * 对接后端 StatisticsController 的所有接口
 */
class StatisticsService {
  private baseURL = 'http://localhost:5215/api/Statistics'

  /**
   * 获取库存数量占比
   * @param params 查询参数
   */
  async getGoodsPercentageNumber(params?: {
    storeId?: number
    category?: string
    topCount?: number
  }): Promise<APIResult<GoodsInventoryNumber>> {
    try {
      const response = await axios.get(`${this.baseURL}/GetGoodsPercentageNumber`, {
        params,
        timeout: 10000
      })
      return response.data
    } catch (error) {
      console.error('获取库存数量占比失败:', error)
      throw error
    }
  }

  /**
   * 获取库存金额占比
   * @param params 查询参数
   */
  async getInventoryAmountRatio(params?: {
    storeId?: number
    category?: string
    topCount?: number
  }): Promise<APIResult<InventoryAmountRatio>> {
    try {
      const response = await axios.get(`${this.baseURL}/GetInventoryAmountRatio`, {
        params,
        timeout: 10000
      })
      return response.data
    } catch (error) {
      console.error('获取库存金额占比失败:', error)
      throw error
    }
  }

  /**
   * 获取出入库排名统计
   * @param params 查询参数
   */
  async getInOutboundRanking(params: {
    isInbound: boolean
    startDate?: string
    endDate?: string
    storeId?: number
    topCount?: number
  }): Promise<APIResult<InOutboundRanking>> {
    try {
      const response = await axios.get(`${this.baseURL}/GetInOutboundRanking`, {
        params,
        timeout: 10000
      })
      return response.data
    } catch (error) {
      console.error('获取出入库排名失败:', error)
      throw error
    }
  }

  /**
   * 获取出入库统计数据
   * @param params 查询参数
   */
  async getInOutboundStatistics(params?: {
    startDate?: string
    endDate?: string
    storeId?: number
    goodsId?: number
    includeDailyDetails?: boolean
  }): Promise<APIResult<InOutboundStatistics>> {
    try {
      const response = await axios.get(`${this.baseURL}/GetInOutboundStatistics`, {
        params,
        timeout: 10000
      })
      return response.data
    } catch (error) {
      console.error('获取出入库统计失败:', error)
      throw error
    }
  }

  /**
   * 获取库存预警信息
   * @param params 查询参数
   */
  async getLowStockAlert(params?: {
    storeId?: number
    alertLevel?: number
    category?: string
  }): Promise<APIResult<LowStockAlert>> {
    try {
      const response = await axios.get(`${this.baseURL}/GetLowStockAlert`, {
        params,
        timeout: 10000
      })
      return response.data
    } catch (error) {
      console.error('获取库存预警失败:', error)
      throw error
    }
  }

  /**
   * 获取综合仪表板数据
   * 这是主要的数据获取接口，包含所有统计信息
   */
  async getDashboardData(): Promise<APIResult<DashboardData>> {
    try {
      const response = await axios.get(`${this.baseURL}/GetDashboardData`, {
        timeout: 15000 // 综合数据可能需要更长时间
      })
      return response.data
    } catch (error) {
      console.error('获取仪表板数据失败:', error)
      throw error
    }
  }

  /**
   * 发送入库成功消息（用于测试SignalR推送）
   * @param params 消息参数
   */
  async sendInboundSuccessMessage(params: {
    goodsName: string
    quantity: number
    operatorName: string
  }): Promise<APIResult<boolean>> {
    try {
      const response = await axios.post(`${this.baseURL}/SendInboundSuccessMessage`, null, {
        params,
        timeout: 5000
      })
      return response.data
    } catch (error) {
      console.error('发送入库成功消息失败:', error)
      throw error
    }
  }

  /**
   * 发送出库成功消息（用于测试SignalR推送）
   * @param params 消息参数
   */
  async sendOutboundSuccessMessage(params: {
    goodsName: string
    quantity: number
    operatorName: string
  }): Promise<APIResult<boolean>> {
    try {
      const response = await axios.post(`${this.baseURL}/SendOutboundSuccessMessage`, null, {
        params,
        timeout: 5000
      })
      return response.data
    } catch (error) {
      console.error('发送出库成功消息失败:', error)
      throw error
    }
  }

  /**
   * 批量刷新所有数据
   * 用于手动触发数据更新
   */
  async refreshAllData(): Promise<{
    dashboard: APIResult<DashboardData>
    quantityRatio: APIResult<GoodsInventoryNumber>
    amountRatio: APIResult<InventoryAmountRatio>
    inboundRanking: APIResult<InOutboundRanking>
    outboundRanking: APIResult<InOutboundRanking>
    statistics: APIResult<InOutboundStatistics>
    alerts: APIResult<LowStockAlert>
  }> {
    try {
      // 并行请求所有数据
      const [
        dashboard,
        quantityRatio,
        amountRatio,
        inboundRanking,
        outboundRanking,
        statistics,
        alerts
      ] = await Promise.all([
        this.getDashboardData(),
        this.getGoodsPercentageNumber({ topCount: 10 }),
        this.getInventoryAmountRatio({ topCount: 10 }),
        this.getInOutboundRanking({ isInbound: true, topCount: 10 }),
        this.getInOutboundRanking({ isInbound: false, topCount: 10 }),
        this.getInOutboundStatistics({
          startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          endDate: new Date().toISOString().split('T')[0]
        }),
        this.getLowStockAlert()
      ])

      return {
        dashboard,
        quantityRatio,
        amountRatio,
        inboundRanking,
        outboundRanking,
        statistics,
        alerts
      }
    } catch (error) {
      console.error('批量刷新数据失败:', error)
      throw error
    }
  }
}

// 创建单例实例
export const statisticsService = new StatisticsService()

// 导出服务类用于依赖注入
export default StatisticsService
